'use client' // 添加这一行将组件标记为客户端组件
import Image from "next/image";
import { CopilotSidebar } from "@copilotkit/react-ui";
import { useCoAgent, useCoAgentStateRender, useCopilotAction, useLangGraphInterrupt, useCopilotReadable } from "@copilotkit/react-core";
import { useState, useEffect } from "react";

type SampleGraphState = {
  agent_name?: string;
  session_id?: string;
  language?: "英语" | "中文";
  searches?: {
    query: string;
    done: boolean;
  }[];
  knowledge_index?: string;
  knowledge?: string;
}



export default function Home() {
  // styles omitted for brevity
  useCoAgentStateRender<SampleGraphState>({
    name: "sample_agent", // the name the agent is served as
    render: ({ state }) => (
      <div>
        {state.searches?.map((search, index) => (
          <div key={index}>
            {search.done ? "✅" : "❌"} {search.query}{search.done ? "" : "..."}
          </div>
        ))}
      </div>
    ),
  });




  return (
    <>
      <CopilotSidebar
        defaultOpen={true}
        instructions={"You are assisting the user as best as you can. Answer in the best way possible given the data you have."}
        labels={{
          title: "Sidebar Assistant",
          initial: "How can I help you today?",
        }}
      >

      </CopilotSidebar>
      <YourMainContent></YourMainContent>

    </>
  );
}
function YourMainContent() {
  // ... 
  const { state, setState } = useCoAgent<SampleGraphState>({
    name: "sample_agent", // the name the agent is served as
    initialState: { language: "中文", knowledge_index: "" }, // 初始化state
    config: {
      configurable: {
        authTokenFrom_useCoAgent: 'sample_agent-token'
      },
    }
  })
  // 定义知识库选项 实际这里有个从后端获取
  const knowledgeOptions = [
    { value: "", label: "不使用知识库" },
    { value: "knowledge:knowledge:1中华人民共和国票据法", label: "中华人民共和国票据法" },
    { value: "knowledge:knowledge:2票据管理实施办法", label: "票据管理实施办法" },
    { value: "knowledge:knowledge:3中华人民共和国反恐怖主义法", label: "中华人民共和国反恐怖主义法" },
    { value: "knowledge:knowledge:4中华人民共和国反洗钱法（新版）", label: "中华人民共和国反洗钱法（新版）" },
    { value: "knowledge:knowledge:5涉及恐怖活动资产冻结管理办法.docx", label: "涉及恐怖活动资产冻结管理办法" },
    { value: "knowledge:knowledge:35涉及恐怖.docx", label: "涉及恐怖活动相关知识" }
  ];
  // 处理知识库选择变化
  const handleKnowledgeChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setState(prev => ({
      ...prev,
      knowledge_index: e.target.value
    }));
  };
  const [user, setUser] = useState({
    name: "张三",
    email: "zhangsan@example.com",
    role: "管理员",
    lastLogin: "2023-10-15"
  });

  const toggleLanguage = () => {
    setState(prev => ({
      ...prev,
      language: prev?.language === "中文" ? "英语" : "中文"
    }));
  };


  // 向 Copilot 提供用户信息
  useCopilotReadable({
    description: "当前登录用户的信息",
    value: user
  });

  //   useCopilotAction({
  //   name: "get_weather_card",
  //   available: "disabled", // Don't allow the agent or UI to call this tool as its only for rendering
  //   render: ({status, args,result}) => {
  //     return (
  //       <p className="text-gray-500 mt-2">
  //         {status !== "complete" && "Calling weather API..."}
  //         {status === "complete" && `Called the weather API for ${args.location}.`}
  //         {JSON.stringify(args)}
  //         {JSON.stringify(result)}


  //       </p>
  //     );
  //   },
  // });
  useLangGraphInterrupt({
    render: ({ event, resolve }) => {
      // 获取中断请求
      const approvalRequest = event.value;
      // 不同中断类型不同处理
      if (approvalRequest.type === "tool_approval_request") {
        return (
          <div style={{ padding: '20px', border: '1px solid #ccc', borderRadius: '8px', maxWidth: '500px' }}>
            <h3>工具调用请求审批</h3>
            <div style={{ marginBottom: '15px', padding: '10px', backgroundColor: '#f5f5f5', borderRadius: '4px' }}>
              <h4>工具名称: {approvalRequest.tool_name}</h4>
              <p><strong>时间:</strong> {approvalRequest.timestamp}</p>
              <p><strong>工具ID:</strong> {approvalRequest.tool_id}</p>
              <div>
                <strong>参数:</strong>
                <pre style={{
                  backgroundColor: '#eee',
                  padding: '8px',
                  borderRadius: '4px',
                  whiteSpace: 'pre-wrap',
                  wordBreak: 'break-all',
                  fontSize: '12px'
                }}>
                  {JSON.stringify(approvalRequest.tool_args, null, 2)}
                </pre>
              </div>
            </div>

            <div style={{ display: 'flex', gap: '10px', justifyContent: 'flex-end', marginTop: '20px' }}>
              <button
                onClick={() => resolve("rejected")}
                style={{
                  padding: '8px 16px',
                  backgroundColor: '#f44336',
                  color: 'white',
                  border: 'none',
                  borderRadius: '4px',
                  cursor: 'pointer'
                }}
              >
                拒绝
              </button>
              <button
                onClick={() => resolve("approved")}
                style={{
                  padding: '8px 16px',
                  backgroundColor: '#4CAF50',
                  color: 'white',
                  border: 'none',
                  borderRadius: '4px',
                  cursor: 'pointer'
                }}
              >
                接受
              </button>
            </div>
          </div>
        );
      }
      else if (approvalRequest.type === "getname_approval_request") {
        return (
          <div>
            <p>{approvalRequest.message}</p>
            <form onSubmit={(e) => {
              e.preventDefault();
              resolve((e.target as HTMLFormElement).response.value);
            }}>
              <input type="text" name="response" placeholder="输入名字" />
              <button type="submit">提交</button>
            </form>
          </div>
        );
      }
      else if (approvalRequest.type === "tool_result_approval_request") {
        // 解析工具调用结果
        let toolResult;
        try {
          toolResult = typeof approvalRequest.tool_result === 'string'
            ? JSON.parse(approvalRequest.tool_result)
            : approvalRequest.tool_result;
        } catch (e) {
          toolResult = approvalRequest.tool_result;
        }

        // 通用的结果展示和编辑组件
        const renderResultField = (key: string, value: any, onChange: (newValue: any) => void) => {
          if (typeof value === 'object' && value !== null) {
            return (
              <div key={key} style={{ marginBottom: '10px' }}>
                <label><strong>{key}:</strong></label>
                <div style={{ marginLeft: '15px', border: '1px solid #eee', padding: '10px', borderRadius: '4px' }}>
                  {Object.entries(value).map(([subKey, subValue]) =>
                    renderResultField(subKey, subValue, (newValue) => {
                      const updatedValue = { ...value, [subKey]: newValue };
                      onChange(updatedValue);
                    })
                  )}
                </div>
              </div>
            );
          } else {
            return (
              <div key={key} style={{ marginBottom: '10px' }}>
                <label><strong>{key}:</strong></label>
                <input
                  type={typeof value === 'number' ? 'number' : 'text'}
                  value={value}
                  onChange={(e) => {
                    const newValue = typeof value === 'number' ?
                      (e.target.value === '' ? 0 : parseFloat(e.target.value)) :
                      e.target.value;
                    onChange(newValue);
                  }}
                  style={{
                    width: '100%',
                    padding: '5px',
                    marginLeft: '10px',
                    borderRadius: '4px',
                    border: '1px solid #ccc'
                  }}
                />
              </div>
            );
          }
        };

        // 创建可编辑的结果对象
        const [editableResult, setEditableResult] = useState(toolResult);

        return (
          <div style={{ padding: '20px', border: '1px solid #ccc', borderRadius: '8px', maxWidth: '600px' }}>
            <h3>工具调用结果审核</h3>
            <p>请审核以下工具调用结果，您可以选择接受或修改后提交：</p>

            <div style={{
              marginTop: '15px',
              padding: '15px',
              backgroundColor: '#f9f9f9',
              borderRadius: '4px',
              maxHeight: '400px',
              overflowY: 'auto'
            }}>
              {Object.entries(editableResult).map(([key, value]) =>
                renderResultField(key, value, (newValue) => {
                  setEditableResult((prev: typeof editableResult) => ({
                    ...prev,
                    [key]: newValue
                  }));
                })
              )}
            </div>

            <div style={{ display: 'flex', gap: '10px', justifyContent: 'flex-end', marginTop: '20px' }}>
              <button
                type="button"
                onClick={() => resolve(approvalRequest.tool_result)}
                style={{
                  padding: '8px 16px',
                  backgroundColor: '#4CAF50',
                  color: 'white',
                  border: 'none',
                  borderRadius: '4px',
                  cursor: 'pointer'
                }}
              >
                接受结果
              </button>
              <button
                type="button"
                onClick={() => resolve(JSON.stringify(editableResult))}
                style={{
                  padding: '8px 16px',
                  backgroundColor: '#2196F3',
                  color: 'white',
                  border: 'none',
                  borderRadius: '4px',
                  cursor: 'pointer'
                }}
              >
                修改后提交
              </button>
            </div>
          </div>
        );
      }
      else {
        return (
          <div>
            <p>未知的中断请求</p>
            <button onClick={() => resolve("rejected")}>关闭</button>
          </div>

        )
      }

    }
  });

  //   useLangGraphInterrupt({
  //     render: ({ event, resolve }) => (
  //         <div>
  //             <p>{event.value}</p>
  //             <form onSubmit={(e) => {
  //                 e.preventDefault();
  //                 resolve((e.target as HTMLFormElement).response.value);
  //             }}>
  //                 <input type="text" name="response" placeholder="Enter your response" />
  //                 <button type="submit">Submit</button>
  //             </form>
  //         </div>
  //     )
  // });
  useCopilotAction({
    name: "get_weather_card",
    followUp: false,
    description: "获取指定位置的天气信息。",
    available: "disabled", // 保持为disabled，确保不被当作前端工具
    render: ({ status, args }) => {
      return (
        <div className="text-gray-500 mt-2">
          {status !== "complete" && "Calling weather API..."}
          {/* {status === "complete" && `Called the weather API for ${args.location}.`} */}
          {<WeatherCard location={args.location} result={args} themeColor="#3b82f6" />}
          <pre className="text-gray-500 text-sm">
            {`工具调用结果: ${JSON.stringify(args, null, 2)}`}
          </pre>
        </div>
      );
    },
  });

  return (
    <div>
      <div className="mt-4">
        <label htmlFor="knowledge-select" className="block text-sm font-medium text-gray-700 mb-1">
          选择知识库:
        </label>
        <select
          id="knowledge-select"
          value={state.knowledge_index || ""}
          onChange={handleKnowledgeChange}
          className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
        >
          {knowledgeOptions.map((option) => (
            <option key={option.value} value={option.value}>
              {option.label}
            </option>
          ))}
        </select>
        {state.knowledge_index && (
          <p className="mt-2 text-sm text-gray-500">
            当前使用知识库: {knowledgeOptions.find(opt => opt.value === state.knowledge_index)?.label}
          </p>
        )}
      </div>
      <p>Language: {state.language}</p>
      <p>agentname: {state.agent_name}</p>
      <p>knowledge_index: {state.knowledge_index}</p>

      <p>knowledge: {state.knowledge}</p>

      <button onClick={toggleLanguage} className="px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white font-medium rounded-lg shadow-md transition-all duration-200 ease-in-out transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-blue-300 focus:ring-opacity-50">
        切换语言 (当前: {state.language})
      </button>
      {/* ... */}
      <div className="flex flex-col gap-2 mt-4">
        {state.searches?.map((search, index) => (
          <div key={index} className="flex flex-row">
            {search.done ? "✅" : "❌"} {search.query}
          </div>
        ))}
      </div>

    </div>
  )
}
function SunIcon() {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className="w-14 h-14 text-yellow-200">
      <circle cx="12" cy="12" r="5" />
      <path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42" strokeWidth="2" stroke="currentColor" />
    </svg>
  );
}
function WeatherCard({ location, result, themeColor }: { location?: string, result?: any, themeColor: string }) {
  // 调试输出 - 每次result变化时输出
  useEffect(() => {
    console.log("WeatherCard result:", result);
  }, [result]);

  return (
    <div
      style={{ backgroundColor: themeColor }}
      className="rounded-xl shadow-xl mt-6 mb-4 max-w-md w-full"
    >
      <div className="bg-white/20 p-4 w-full">
        <div className="flex items-center justify-between">
          <div>
            <h3 className="text-xl font-bold text-white capitalize">{location}</h3>
            <p className="text-white">天气</p>
          </div>
          <SunIcon />
        </div>

        <div className="mt-4 flex items-end justify-between">
          <div className="text-3xl font-bold text-white">{result.temperature}</div>
          <div className="text-sm text-white">{result.condition}</div>
        </div>

        <div className="mt-4 pt-4 border-t border-white">
          <div className="grid grid-cols-3 gap-2 text-center">
            <div>
              <p className="text-white text-xs">湿度</p>
              <p className="text-white font-medium">{result.humidity}</p>
            </div>
            <div>
              <p className="text-white text-xs">风速</p>
              <p className="text-white font-medium">{result.wind.speed}级</p>
            </div>
            <div>
              <p className="text-white text-xs">日期</p>
              <p className="text-white font-medium">{result.updated_at?.substring(0, 10)}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
